package tour.general.video;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.GregorianCalendar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import tour.general.BaseActivity;
import tour.general.R;
import tour.general.adapter.VideoAdapter;
import tour.general.util.Parser;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.dropbox.client2.DropboxAPI;
import com.dropbox.client2.android.AndroidAuthSession;
import com.dropbox.client2.exception.DropboxException;
import com.dropbox.client2.session.AccessTokenPair;
import com.dropbox.client2.session.AppKeyPair;
import com.dropbox.client2.session.Session.AccessType;

public class VideoActivity extends BaseActivity {
	private JSONArray mVideoArray;
	private ListView mVideoList;
	private VideoAdapter mVideoAdapter;

	private final boolean TEST = false;

	final static private String APP_KEY = "ccavaavvoav0kfb";
	final static private String APP_SECRET = "f4oxvnhltw1u7nn";
	final static private AccessType ACCESS_TYPE = AccessType.DROPBOX;
	private DropboxAPI<AndroidAuthSession> mDBApi;
	final static private String ACCOUNT_KEY = "v2kxrus29yr5zti";
	final static private String ACCOUNT_SECRET = "brt624n058g87jy";

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.videos);
		initToolbar();

		try {

			// init DROPBOX
			AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET);
			AndroidAuthSession session = new AndroidAuthSession(appKeys, ACCESS_TYPE);
			mDBApi = new DropboxAPI<AndroidAuthSession>(session);

			// per reperire account_key e account_secret, da fare solo una
			// volta.
			// mDBApi.getSession().startAuthentication(VideoActivity.this);

			mDBApi.getSession().setAccessTokenPair(new AccessTokenPair(ACCOUNT_KEY, ACCOUNT_SECRET));

			if (TEST) {
				downloadDropboxFile();
				initActivity();
			} else {
				SharedPreferences settings = getSharedPreferences("giro", Activity.MODE_PRIVATE);
				if (settings != null) {
					String data = settings.getString("giornoLink", "");

					GregorianCalendar gc = new GregorianCalendar();
					int giorno = gc.get(GregorianCalendar.DAY_OF_MONTH);
					int mese = (gc.get(GregorianCalendar.MONTH)) + 1;
					int anno = gc.get(GregorianCalendar.YEAR);

					String date_now = giorno + "" + mese + "" + anno;

					if (date_now.equals(data)) {
						initActivity();
					} else {
						downloadDropboxFile();
						initActivity();
					}
					SharedPreferences.Editor editor = settings.edit();

					editor.putString("giornoLink", date_now);
					editor.commit();

				}
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
		// END

	}

	private void initActivity() {
		mVideoArray = Parser.getInstance().createArrayJsonLink(this);

		mVideoAdapter = new VideoAdapter(this, mVideoArray);
		mVideoList = (ListView) findViewById(R.id.list_stages);
		mVideoList.setAdapter(mVideoAdapter);

		mVideoList.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				/*
				 * Intent intent = new Intent(VideoActivity.this,
				 * WebViewGiroMobile.class);
				 * 
				 * 
				 * startActivity(intent);
				 */

				JSONObject o = null;
				o = (JSONObject) mVideoList.getItemAtPosition(position);
				String url = "";
				try {
					url = o.getString("link");
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube://" + url));
				startActivity(intent);

				// startActivity(new Intent(Intent.ACTION_VIEW,
				// Uri.parse("http://www.youtube.com/watch?v=cxLG2wtE7TM")));
			}
		});

	}

	protected void onResume() {
		super.onResume();

		// ...

		// da fare solo la prima volta per le key
		// if (mDBApi.getSession().authenticationSuccessful()) {
		// try {
		// // MANDATORY call to complete auth.
		// // Sets the access token on the session
		// mDBApi.getSession().finishAuthentication();
		//
		// AccessTokenPair tokens = mDBApi.getSession().getAccessTokenPair();
		//
		// mDBApi.getSession().setAccessTokenPair(tokens);
		//
		// Log.d("dd", tokens.toString());
		//
		// downloadDropboxFile();
		//
		// // Provide your own storeKeys to persist the access token pair
		// // A typical way to store tokens is using SharedPreferences
		// } catch (IllegalStateException e) {
		// Log.i("DbAuthLog", "Error authenticating", e);
		// } catch (IOException e) {
		// e.printStackTrace();
		// }
		// }

		// ...
	}

	private boolean downloadDropboxFile() throws IOException {

		File dir = new File(Environment.getExternalStorageDirectory() + "/tourdefrance");
		if (!dir.exists()) {
			dir.mkdirs();
		}

		File file = new File(Environment.getExternalStorageDirectory() + "/tourdefrance/link.json");
		if (file.exists()) {
			file.delete();
		}
		file = new File(Environment.getExternalStorageDirectory() + "/tourdefrance/link.json");

		OutputStream out = null;
		try {
			out = new BufferedOutputStream(new FileOutputStream(file));
			mDBApi.getFile("/Public/tour_youtube_link.json", null, out, null);
			// Log.i("DbExampleLog", "The file's rev is: " +
			// info.getMetadata().rev);
			// Log.i("DbExampleLog", "The file's contents are: " + new
			// String(out.toString()));
		} catch (DropboxException e) {
			// Log.e("DbExampleLog", "Something went wrong while downloading.");
			e.printStackTrace();
		}

		return true;
	}

}
